// src/main/java/com/example/usermanagement/controller/LoginController.java
package com.example.usermanagement.controller;

import com.example.usermanagement.dto.request.LoginRequest;
import com.example.usermanagement.dto.response.CommonResponse;
import com.example.usermanagement.entity.SysUser;
import com.example.usermanagement.service.SysUserService;
import com.example.usermanagement.util.JwtUtil;
import com.example.usermanagement.util.PasswordUtils; // ✅ 新增：导入 PasswordUtils
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/dev-api/user")
@Tag(name = "用户登录", description = "登录登出接口")
public class LoginController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 用户登录
     * 流程：
     * 1. 根据用户名查询用户
     * 2. 对用户输入的密码进行 MD5 加密
     * 3. 与数据库中的加密密码比对
     * 4. 验证通过后生成 JWT Token
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public CommonResponse<Map<String, String>> login(@Valid @RequestBody LoginRequest request) {
        // 1. 查询用户
        SysUser user = sysUserService.getUserByUsername(request.getUsername());
        if (user == null) {
            return CommonResponse.fail(401, "用户名或密码错误");
        }

        // 2. ✅ 对用户输入的密码进行 MD5 加密（关键修复）
        String encryptedInputPassword = PasswordUtils.md5Encrypt(request.getPassword());

        // 3. 与数据库中存储的加密密码比对
        if (!encryptedInputPassword.equals(user.getPassword())) {
            return CommonResponse.fail(401, "用户名或密码错误");
        }

        // 4. 生成 JWT Token
        String token = jwtUtil.generateToken(user.getUsername());
        Map<String, String> data = new HashMap<>();
        data.put("token", token);

        return CommonResponse.success(data);
    }

    /**
     * 获取用户信息（前端用 token 换取用户信息）
     */
    @GetMapping("/info")
    @Operation(summary = "获取用户信息")
    public CommonResponse<Map<String, Object>> userInfo(HttpServletRequest request) {
        // 从 X-Token 请求头中获取 token
        String token = request.getHeader("X-Token");
        if (token == null || token.trim().isEmpty()) {
            return CommonResponse.fail(401, "未提供认证令牌，请重新登录");
        }

        try {
            // 从 token 中解析出用户名
            String username = jwtUtil.getUsernameFromToken(token);
            if (username == null) {
                return CommonResponse.fail(401, "无效的Token");
            }

            SysUser user = sysUserService.getUserByUsername(username);
            if (user == null) {
                return CommonResponse.fail(401, "用户不存在");
            }

            Map<String, Object> data = new HashMap<>();
            data.put("roles", new String[]{"admin"});
            data.put("introduction", "系统管理员");
            data.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            data.put("name", user.getFullName());

            return CommonResponse.success(data);
        } catch (Exception e) {
            return CommonResponse.fail(401, "无效的Token");
        }
    }

    /**
     * 用户登出
     * （当前为无状态 JWT，服务端不存储 Token，登出由前端清除 Token 实现）
     */
    @PostMapping("/logout")
    @Operation(summary = "用户登出")
    public CommonResponse<Void> logout() {
        return CommonResponse.success();
    }
}